package com.ruike.alisurface.ui.payPage;

import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.adapter.PayCarListAdapter;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.ui.mainPage.MainActivity;
import com.ruike.alisurface.utils.BannerImageLoader;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.utils.ShareKey.Type_toGoshopzl;

/**
 * Author: voodoo
 * CreateDate: 2020-03-31 031 下午 09:20
 * Description: 选择支付方式
 */
public class SelectPayTypeActivity extends BaseAty {

    @BindView(R.id.selectPay_countDown_tv)
    TextView selectPayCountDownTv;
    @BindView(R.id.selectPay_goback_imgv)
    ImageView selectPayGobackImgv;

    @BindView(R.id.selectPay_goodsList_recv)
    RecyclerView selectPayGoodsListRecv;
    List<CarGoodsBeans> paycarlist;
    @BindView(R.id.pay_type_qrcode)
    ImageView payTypeQrCode;

    @BindView(R.id.pay_type_yhmj)
    TextView payTypeYhmj;
    @BindView(R.id.pay_type_yhljm)
    TextView payTypeYhljm;
    @BindView(R.id.pay_type_mjyh)
    RelativeLayout payTypeMjyh;
    @BindView(R.id.pay_type_zklv)
    TextView payTypeZklv;
    @BindView(R.id.pay_type_zkyh)
    RelativeLayout payTypeZkyh;
    @BindView(R.id.layout_yhhd)
    LinearLayout layout_yhhd;
    @BindView(R.id.selectPay_pupdialog_tv)
    TextView selectPay_pupdialog_tv;


    static Timer timer;//计时
    ArrayList<String> aldatas = new ArrayList<>();//广告集合类
    Dialog dialogs;//显示弹窗

    @Override
    protected boolean getCanToOtherApp() {
        return true;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_select_pay;
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(120, selectPayCountDownTv, MainActivity.class);

        boolean isOpenWEAliPay = ShareUtils.getInstance().getBoolean(ShareKey.IS_OPEN_WEALIPAY_PAY, true); // 启用 扫码支付
        payTypeQrCode.setVisibility(isOpenWEAliPay ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void initViews() {
//        MchApiHttp.getActivityType(this);
        MchApiHttp.get_Materiel(this);
        Constant.showShop = true;
        L.i("选择出货方式页==" + this.getClass().getName());
        initTitleBar(false);
        selectPay_pupdialog_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialogs != null && !dialogs.isShowing()) {
                    dialogs.show();
                } else {
                    AliHuoDongDialog(2);
                }
            }
        });
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("get_materiel")) {
            try {
                selectPay_pupdialog_tv.setVisibility(View.VISIBLE);
                JSONObject jsonObject = new JSONObject(requestJsonStr);
                JSONArray data = jsonObject.getJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    aldatas.add(data.getString(i));
                }
                startTopAdvFileService(Constant.alAdvpath, aldatas);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("get_materiel")) {
            selectPay_pupdialog_tv.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        try {
            paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        } catch (Exception e) {
            L.i("Exception==", e.getLocalizedMessage());
        }
        if (paycarlist != null && paycarlist.size() > 0) {
            selectPayGoodsListRecv.setLayoutManager(new GridLayoutManager(this, paycarlist.size()));
            selectPayGoodsListRecv.setHasFixedSize(true);
            selectPayGoodsListRecv.setAdapter(new PayCarListAdapter(this, paycarlist));
        }
    }

    //    PopupDialog popupDialog;
    int paytype; // 1刷脸  2扫码支付  3卡支付

    @OnClick({R.id.selectPay_goback_imgv, R.id.pay_type_qrcode})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.selectPay_goback_imgv:
                startCountdownTimer(0, null, MainActivity.class);
                break;
            case R.id.pay_type_qrcode: // 扫码支付
                IntentActivity(2);
                break;
        }
    }

    /**
     * 支付类型的判断 及发送能否通信的指令即返回值操作
     * 跳转到不同的页面
     *
     * @param type
     */
    private void IntentActivity(int type) {
        if (paycarlist == null) {
            showLongTip("商品数据异常，请重新选择商品", 5000);
            return;
        }
        paytype = type;
        // 通过发送灯光指令判断是否能够通讯
        Ttys3Utils.getInstance().LEDSetting(10, "0", "2", "1", 70, 15);
        if (timer == null) {
            timer = new Timer();
        }
        L.i("通信计时1====开始");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        L.i("通信计时2====结束");
                        alt();
                    }
                });
            }
        }, 3000);
        if (BuildConfig.DEBUG) {
            EventBus.getDefault().post(new MsgEventBus(Type_toGoshopzl, ""));
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Constant.showShop = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dlCancal();
    }

    CustomDialog dialog;

    /**
     * 通讯异常提示框
     */
    private void alt() {
        try {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            dialog = new CustomDialog.Builder(this)
                    .setTitle("温馨提示").setMessage("底层通信出现异常，暂时停止购买，请稍后重试!!!")
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                        }
                    })
                    .setTouchOutsideCloseDialog(false).create();
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String Tag = getClass().getCanonicalName();

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_toGoshopzl)) {
            if (timer != null) {
                timer.cancel();
                timer.purge();
                timer = null;
            }
            L.i(Tag + "--购买前的通信指令---" + event.getMessage() + " =跳转类型=" + paytype);
            if (paytype == 1) {
                startActivity(PayAlFaceActivity.class, null);
            } else if (paytype == 2) {
                startActivity(PayForQRCodeActivity.class, null);
            } else if (paytype == 3) {
                startActivity(PayForPolymerizationActivity.class, null);
            }
            if (paytype > 0) {
                finish();
            }
        }
        if (event.getType().equals("topadv")) {
            AliHuoDongDialog(1);
        }
    }

    /**
     * 活动显示数据判断
     *
     * @param now_activity_id
     * @param activity_json
     * @throws JSONException
     */
    public void setDataHuoDong(String now_activity_id, String activity_json) throws JSONException {
        if (TextUtils.isEmpty(now_activity_id)) {

            return;
        }
        if (now_activity_id.equals("1")) {  // 转盘
            layout_yhhd.setVisibility(View.GONE);

            return;
        }
        if (TextUtils.isEmpty(activity_json)) {

            return;
        }

        JSONObject Js = new JSONObject(activity_json);
        if (now_activity_id.equals("2")) {  //满减

            layout_yhhd.setVisibility(View.VISIBLE);
            payTypeMjyh.setVisibility(View.VISIBLE);
            payTypeZkyh.setVisibility(View.GONE);
            String full = Js.optString("full", "");
            String reduce = Js.optString("reduce", "");
            payTypeYhmj.setText(full + "");
            payTypeYhljm.setText(reduce + "");

            return;
        }
        if (now_activity_id.equals("3")) {  //折扣

            layout_yhhd.setVisibility(View.VISIBLE);
            payTypeZkyh.setVisibility(View.VISIBLE);
            payTypeMjyh.setVisibility(View.GONE);
            String off_rate = Js.optString("off_rate", "0");
            int zhek = Double.valueOf(off_rate).intValue();
            payTypeZklv.setText(zhek + "");

            return;
        }
    }


    public void AliHuoDongDialog(int model) {
        try {
            //1、使用Dialog、设置style
            dialogs = new Dialog(this, R.style.Dialog);
//2、设置布局
            View view = View.inflate(this, R.layout.dialog_custom_layout, null);
            Banner activityBannerBanner = view.findViewById(R.id.dl_Banner_banner);
            ImageView dl_delect = view.findViewById(R.id.dl_delect);
            activityBannerBanner.setIndicatorGravity(BannerConfig.CIRCLE_INDICATOR);

            // 设置图片加载器
            activityBannerBanner.setImageLoader(new BannerImageLoader());
            // 设置banner样式
            activityBannerBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            List<String> advList = new ArrayList<>();
            for (int i = 0; i < aldatas.size(); i++) {
                String Name = aldatas.get(i).substring(aldatas.get(i).lastIndexOf("/")).substring(1);
                File file = new File(Constant.alAdvpath, Name);
                if (file.exists()) {
                    advList.add(file.getAbsolutePath());
                } else {
                    advList.add(aldatas.get(i));
                }
            }
            L.i("top广告活动图片地址==", advList.toString());
            // 设置图片集合
            activityBannerBanner.setImages(advList);
            // 设置自动轮播，默认为true
            activityBannerBanner.isAutoPlay(true);
            // 设置轮播时间单位毫秒
            activityBannerBanner.setDelayTime(3000);
            activityBannerBanner.start();
            dialogs.setContentView(view);
            dialogs.setCancelable(true);
            Window window = dialogs.getWindow();
            //设置弹出位置gh
            window.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = window.getAttributes();
            WindowManager m = this.getWindowManager();
            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
            lp.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.6
            lp.height = (int) (d.getHeight() * 0.7); // 高度设置为屏幕的0.6
            window.setAttributes(lp);
            //设置对话框大小
//        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            dialogs.show();

            dl_delect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    dlCancal();
                }
            });

           /* dialogs.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (activityBannerBanner != null) {
                        activityBannerBanner.stopAutoPlay();
                        activityBannerBanner.releaseBanner();
                    }
                }
            });*/

            if (model == 1) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        dlCancal();
                    }
                }, 3000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void dlCancal() {
        if (dialogs != null && dialogs.isShowing()) {
            dialogs.dismiss();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String data) {
        super.onError(requestUrl, errorMsg, data);
    }
}
